package jwdt.xadmin;

import javax.servlet.http.HttpServletRequest;

import jwdt.common.action.BaseAction;
import jwdt.xadmin.system.bean.TSystem;
import jwdt.xadmin.system.bean.TUser;

import com.ezerg.util.DateUtil;
import com.ezerg.web.Form;
import com.ezerg.web.Module;
import com.ezerg.web.Page;
import com.ezerg.web.annotation.Controller;
import com.ezerg.web.annotation.RequestMapping;
import com.ezerg.web.ext.HttpServletRequestAware;

@Controller
public class LoginAction extends BaseAction implements HttpServletRequestAware {

	private HttpServletRequest request;

	@RequestMapping("/adminlogin")
	public Page doAdminLogin(Form f, Module m) throws Exception {
		f.add("syscfg", jdb.get(TSystem.class, 1));
		return m.defaultPage();
	}
	
	@RequestMapping("/adminLoginAct")
	public Page doLogin(Form f, Module m) throws Exception {
		String url = f.getString("url", "xadmin/adminindex.do");
		//
		String username = f.getString("username");
		String password = f.getString("password");
		String sql = "select userid from t_user where username=? and userpassword=md5(?) and jinyong=0";
		Object userid = jdb.uniqueResult(sql, new Object[]{username, password});
		if(userid == null) {
			f.add("ret", "用户名或密码错误，请重新输入！").add("url", "adminlogin.do");
			return m.findPage("tips");
		}
		TUser userInfo = (TUser)jdb.get(TUser.class, userid);
		TUser user = new TUser();
		user.setUserid(userInfo.getUserid());
		user.setUserlogins(userInfo.getUserlogins()+1);
		user.setLastlogin(DateUtil.getDateTime());
		user.setUserlastip(request.getRemoteAddr());
		jdb.update(user);
		//
		userInfo = (TUser)jdb.get(TUser.class, userid);
		//userInfo.setAuthority(jdb.querySingle("SELECT cddm FROM jwdt_qx_jscd WHERE jsdm=?", new Object[]{userInfo.getOskey()}));
		f.setSession("userInfo", userInfo);
		return m.getRedirectPage(url);
	}

	@Override
	public void setHttpServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	@RequestMapping("/xadmin/adminLogoutAct")
	public Page doExit(Form f, Module m) throws Exception {
		f.setSession("userInfo", null);
		return m.getRedirectPage("/adminlogin.do");
	}
	
}
